/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.rest.xml;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;

public class AttributeSupport {
    private final AttributesAdaptor attrs;
    
    private static interface AttributesAdaptor {
        public String getValue(String name);
    }
    
    private static class SAXAttributesAdaptor implements AttributesAdaptor {
        private final Attributes attrs;
        
        private SAXAttributesAdaptor(Attributes attrs) {
            this.attrs = attrs;
        }
        
        public String getValue(String name) {
            return attrs.getValue(name);
        } 
    }
    
    private static class DOMAttributesAdaptor implements AttributesAdaptor {
        private final NamedNodeMap attrs;
        
        private DOMAttributesAdaptor(NamedNodeMap map) {
            this.attrs = map;
        }

        public String getValue(String name) {
            Node attrNode = this.attrs.getNamedItem(name);
            if (attrNode != null) {
                return attrNode.getNodeValue();
            } else {
                return null;
            }
        }
    }
    
    public AttributeSupport(final Attributes attrs) {
        this.attrs = new SAXAttributesAdaptor(attrs);    
    }
    
    public AttributeSupport(final NamedNodeMap attrs) {
        this.attrs = new DOMAttributesAdaptor(attrs);
    }
        
    public boolean getAsBoolean(String name) {
        String value = this.attrs.getValue(name);
        
        try {
            int ival = Integer.parseInt(value);
            return (ival == 1);
        } catch (NumberFormatException ignore) {
        }
           
        return Boolean.valueOf(value);
    }
    
    public int getAsInt(String name) {
        String value = this.attrs.getValue(name);
        return Integer.parseInt(value);
    }
    
    public long getAsLong(String name) {
        String value = this.attrs.getValue(name);
        return Long.valueOf(value);
    }
    
    public String get(String name) {
        return this.attrs.getValue(name);    
    }
}
